let userInfoData = {}
let pageSelect;

/**
* 接收后端返回的用户数据并渲染
* @param {object} userInfo 
 */
function renderUserInfo(userInfo) {
    const notSetText = '未设置';
    userInfoData = userInfo;
    console.log("userInfoData",userInfoData)
    // 个人信息标签页的内容
    document.getElementById('info-username').textContent = userInfo.username || notSetText;
    document.getElementById('info-realname').textContent = userInfo.name || notSetText; 
    document.getElementById('info-email').textContent = userInfo.email || notSetText;
    document.getElementById('info-phone').textContent = userInfo.phone || notSetText;
    
    // "修改信息"标签页的表单
    document.getElementById('edit-username').value = userInfoData.username || '';
    document.getElementById('edit-realname').value = userInfoData.name || ''; 
    document.getElementById('edit-email').value = userInfoData.email || '';
    document.getElementById('edit-phone').value = userInfoData.phone || '';
}

/**
 * 渲染文章列表
 * @param {Array} articles 文章列表数据
 */
function renderArticles(articles) {
    const articleList = document.querySelector('.article-list');
    articleList.innerHTML = '';

    articles.forEach(article => {
        const articleHtml = `
            <div class="article-item">
                <div class="article-info">
                    <div class="article-title">${article.title}</div>
                    <div class="article-meta">
                        <span>发布时间：${article.create_time}</span>
                        <span>类型：${article.type_name || '未分类'}</span>
                    </div>
                </div>
                <div class="article-actions">
                    <button class="btn btn-secondary" onclick="editArticle(${article.id})">编辑</button>
                    <button class="btn btn-secondary" onclick="deleteArticle(${article.id})">删除</button>
                </div>
            </div>
        `;
        articleList.insertAdjacentHTML('beforeend', articleHtml);
    });
}

/**
 * 加载用户文章列表
 * @param {number} currentPage 当前页码
 * @param {number} pageSize 每页数量
 */
function loadUserArticles(currentPage = 1, pageSize = 10) {
    const userId = JSON.parse(localStorage.getItem('xlsystem_user')).id;
    
    fetch(`../php/userCenter.php?userId=${userId}&type=mental&currentPage=${currentPage}&pageSize=${pageSize}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const pageData = data.data;  // 获取分页数据对象
                renderArticles(pageData.data);  // 文章数组
                
                // 更新分页器
                const totalPages = Math.ceil(pageData.total / pageData.page_size);
                if (!pageSelect) {
                    pageSelect = new PageSelect('pagination', {
                        currentPage: pageData.current_page,
                        pageSize: pageData.page_size,
                        totalPages: totalPages,
                        onChange: (page, size) => loadUserArticles(page, size)
                    });
                } else {
                    pageSelect.update({
                        currentPage: pageData.current_page,
                        totalPages: totalPages
                    });
                }
            } else {
                console.error('获取文章列表失败:', data.message);
            }
        })
        .catch(error => {
            console.error('请求文章列表时发生错误:', error);
        });
}

// 加载导航栏
document.addEventListener('DOMContentLoaded', function() {
    // 获取用户信息
    getUserById();
    
    // 初始加载文章列表
    loadUserArticles();
    
    // 标签页切换
    const tabs = document.querySelectorAll('.tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            tabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            const contents = document.querySelectorAll('.tab-content');
            contents.forEach(content => content.classList.remove('active'))
            const tabId = this.getAttribute('data-tab');
            document.getElementById(tabId + '-content').classList.add('active');
            
            // 切换到文章管理标签时重新加载文章列表
            if (tabId === 'articles') {
                loadUserArticles();
            }
        });
    });
    
    // 设置表单提交事件
    document.getElementById('edit-profile-form').addEventListener('submit', function(e) {
        e.preventDefault();
        saveUserInfo();
    });
});

// 保存用户信息
function saveUserInfo() {
    // 获取表单数据
    const username = document.getElementById('edit-username').value;
    const realname = document.getElementById('edit-realname').value;
    const email = document.getElementById('edit-email').value;
    const phone = document.getElementById('edit-phone').value;
    // const bio = document.getElementById('edit-bio').value;
    const password = document.getElementById('edit-password').value;
    const passwordConfirm = document.getElementById('edit-password-confirm').value;
    
    // 验证表单
    if (!username) {
        alert('用户名不能为空');
        return;
    }
    
    if (!email) {
        alert('邮箱不能为空');
        return;
    }


    if (password && password !== passwordConfirm) {
        alert('两次输入的密码不一致');
        return;
    }

    const dataToSend = {
        id: userInfoData.id,
        username: username,
        name: realname,
        email: email,
        phone: phone,
        password: password
    };
    console.log("dataToSend",dataToSend)
    fetch("../php/userCenter.php",{
        method:"POST",
        body:JSON.stringify(dataToSend) ,
        headers:{
            "Content-Type":"application/json"
        }
    }).then(res=>res.json()).then(data=>{
        console.log(data)
        if(data.success){
            alert("修改成功")
            getUserById();
            localStorage.setItem("xlsystem_user",JSON.stringify({
                id:userInfoData.id,
                username:dataToSend.username,
            }))
        }else{
            console.log("修改失败")
            alert(data.message)
            // console.log(data)
        }
        // window.location.reload()

    }).catch(err=>{
        console.log(err)
    })
    
    document.querySelector('.tab[data-tab="info"]').click();
}

// 重置表单
function resetForm() {
    document.getElementById('edit-profile-form').reset();
    getUserById();
}

// 文章过滤
function filterArticles(type) {
    // 重新加载文章列表
    loadUserArticles();
}

// 创建新文章
function createNewArticle() {
    console.log('创建新文章');
    // 这里应该跳转到文章编辑页面
    window.location.href = 'editArticle.html';
}

// 编辑文章
function editArticle(id) {
    console.log('编辑文章ID：', id);
    // 这里应该跳转到文章编辑页面
    window.location.href = 'editArticle.html?id=' + id;
}

// 删除文章
function deleteArticle(id) {
    if (confirm('确定要删除这篇文章吗？')) {
        console.log('删除文章ID：', id);


        const formData = new URLSearchParams();
        formData.append('action', 'deleteArticle');
        formData.append('id', id);

        fetch(`../php/editArticle.php`, {
            method: "POST", 
            // headers: {
            //     // 'Content-Type': 'application/x-www-form-urlencoded',
            // },
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            console.log(data);
            if (data.success) {
                alert("删除成功")
                loadUserArticles(); 
            } else {
                alert("删除失败: " + data.message);
            }
        })
        .catch(err => {
            alert("删除操作失败，请检查网络连接或联系管理员。 " + err);
        });
        
    }
}

document.addEventListener('DOMContentLoaded', () => {
    getUserById();
});